package com.liu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.common.R;
import com.liu.dto.SetmealDto;
import com.liu.entity.Category;
import com.liu.entity.Setmeal;
import com.liu.entity.SetmealDish;
import com.liu.service.CategoryService;
import com.liu.service.SetmealDishService;
import com.liu.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Resource
    private SetmealService setmealService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private SetmealDishService setmealDishService;

    /**
     * 新建套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "SetmealCache", allEntries = true)
    @PostMapping()
    public R<String> saveSetmeal(@RequestBody SetmealDto setmealDto) {

        setmealService.saveSetmeslWithDish(setmealDto);

        return R.success("新建套餐成功");
    }


    /**
     * 分页查询套餐
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name != null, Setmeal::getName, name);
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        //执行分页查询
        setmealService.page(pageInfo, lambdaQueryWrapper);

        //拷贝pageInfo的分页信息到dtoPage，除去records---此处拷贝的是分页信息
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        List<Setmeal> records = pageInfo.getRecords();

        //通过Stream流遍历pageInfo的records，得到categoryName，将其拷贝给SetmealDto---此处的records是Setmeal集合
        List<SetmealDto> setmealDtoList = records.stream().map((item) -> {

            SetmealDto setmealDto = new SetmealDto();
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            BeanUtils.copyProperties(item, setmealDto);
            if (category != null) {
                //将categoryName赋值给setmealDto的categoryName
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;

        }).collect(Collectors.toList());

        //将上面得到的SetmealDto类型的records赋值给dtoPage的records
        dtoPage.setRecords(setmealDtoList);

        return R.success(dtoPage);
    }

    /**
     * 通过id查询套餐信息和菜品信息
     *
     * @param id 套餐id
     * @return R
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        //通过id查询套餐信息和菜品信息
        return R.success(setmealService.getSetmealWithDish(id));
    }

    /**
     * 更新套餐状态-1->0 (起售->停售)
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> updateStatus(@RequestParam List<Long> ids) {

        //更新套餐状态
        setmealService.update(new UpdateWrapper<Setmeal>().set("status", 0).in("id", ids));

        return R.success("套餐状态更新成功");
    }


    /**
     * 更新套餐状态-0->1 (停售->起售)
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> updateStatus1(@RequestParam List<Long> ids) {
        //更新套餐状态
        setmealService.update(new UpdateWrapper<Setmeal>().set("status", 1).in("id", ids));

        return R.success("套餐状态更新成功");
    }


    /**
     * 更新套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping()
    public R<String> update(@RequestBody SetmealDto setmealDto) {

        //获取菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().peek((item) -> item.setSetmealId(setmealDto.getId())).collect(Collectors.toList());

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        //删除旧菜品信息
        setmealDishService.remove(queryWrapper);

        //添加新菜品信息
        setmealDishService.saveBatch(setmealDishes);

        //更新套餐信息
        setmealService.updateById(setmealDto);

        return R.success("更新套餐成功");
    }


    /**
     * （批量）删除套餐
     *
     * @param ids 套餐id列表
     * @return R
     */
    @CacheEvict(value = "SetmealCache", allEntries = true)
    @DeleteMapping()
    public R<String> delete(@RequestParam List<Long> ids) {

        setmealService.removeWithDish(ids);

        return R.success("删除套餐成功");
    }


    /**
     * （前台）查询套餐信息
     *
     * @param setmeal
     * @return
     */
    @Cacheable(value = "SetmealCache", key = "#setmeal.getCategoryId()+'_'+#setmeal.getStatus()")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);

    }
}
